<template>
  <div class="container">
    <topTitle
      :titleText="titleText"
      :back="back"
      @gobackTriser="goBack"
      :titleExplain="
        isYcUser() || isYiLingUser()
          ? '可批量对项目进行分配。分配需先选择分配的监察员'
          : '可批量对项目进行分配。分配需先选择分配的网格管理员'
      "
    ></topTitle>
    <div class="mainCon">
      <el-form
        :model="formData"
        label-width="90px"
        :rules="formRules"
        ref="formData"
        class="form formSty"
      >
        <el-form-item label prop="department" class="el-form-department">
          <el-row class="custom-tree-container clearfix">
            <!-- 树形结构部分 -->
            <el-col :span="11" class="treeStyle">
              <div class="girdBox">
                <el-row class="titleSty">
                  <el-col :span="22">
                    <el-checkbox
                      :indeterminate="isIndeterminate"
                      v-model="checked"
                      @change="handleCheckChange"
                    ></el-checkbox>
                    未被分配的项目</el-col
                  >
                  <el-col :span="2" class="sums">
                    {{ checkedCities.length }}/{{ unallocatedProArr.length }}
                  </el-col>
                </el-row>
                <el-form-item
                  label="区域"
                  class="row-padding-bottom"
                  style="margin-bottom: 18px"
                  v-if="isCzUser()"
                >
                  <el-cascader
                    ref="manageArea"
                    v-model="areaId"
                    :append-to-body="false"
                    :options="areasOptions"
                    @change="getAreaId"
                    clearable
                    filterable
                    :props="{ checkStrictly: true }"
                    style="width: 70%"
                  ></el-cascader>
                </el-form-item>
                <el-form-item label="项目名称">
                  <el-select
                    v-model="formData.unallocatedPro"
                    filterable
                    clearable
                    remote
                    reserve-keyword
                    placeholder="请输入"
                    :remote-method="remoteMethod"
                    :loading="loading"
                    @clear="clearOption"
                    style="width: 70%"
                    @change="changePro($event)"
                    value-key="id"
                  >
                    <el-option
                      v-for="item in newUnallocatedProArr"
                      :key="item.id"
                      :label="item.projectName"
                      :value="item"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <ul class="selectDepart treeStyleList" id="choiceNameBox">
                  <el-checkbox-group
                    v-model="checkedCities"
                    @change="handleCheckedCitiesChange"
                  >
                    <el-checkbox
                      v-for="item in unallocatedProArr"
                      :label="item.id"
                      :key="item.id"
                      style="display: block"
                      >{{ item.projectName }}</el-checkbox
                    >
                  </el-checkbox-group>
                </ul>
                <div class="block">
                  <el-pagination
                    layout="total,prev, pager, next"
                    :total="total"
                    :current-page.sync="pageNo"
                    :page-size="pageSize"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :pager-count="4"
                  >
                  </el-pagination>
                </div>
              </div>
            </el-col>
            <el-col
              :span="2"
              class="treeStyle treeStyleCenter"
              style="width: 10%; text-align: center; padding: 185px 0"
            >
              <div style="heigth: 200px">
                <el-button
                  class="saveBtn choseTreeBut disableSty"
                  icon="el-icon-arrow-right"
                  type="primary"
                  @click="confirm()"
                  :disabled="checkedCities.length === 0"
                ></el-button>
                <el-button
                  class="saveBtn choseTreeBut disableSty"
                  icon="el-icon-arrow-left"
                  type="primary"
                  @click="cancel()"
                  style="margin-top: 15px"
                  :disabled="checkedAllCities.length === 0"
                ></el-button>
              </div>
            </el-col>
            <el-col :span="11" class="treeStyle">
              <div class="girdBox">
                <el-row class="titleSty">
                  <el-col :span="22">
                    <el-checkbox
                      :indeterminate="isIndeterminateAll"
                      v-model="checkedAll"
                      @change="handleCheckAllChange"
                    ></el-checkbox>
                    分配给
                    <el-select
                      clearable
                      placeholder="请选择"
                      v-model="formData.gridMember"
                      @change="selectGrid"
                      :no-data-text="
                        isYcUser() || isYiLingUser()
                          ? '请添加项目监管信息'
                          : '请添加网络网格信息'
                      "
                    >
                      <el-option
                        v-for="(item, index) of gridMemberArr"
                        :key="index"
                        :label="item.userName"
                        :value="item.userId"
                      ></el-option>
                    </el-select>
                    的项目
                  </el-col>
                  <el-col :span="2" class="sums">
                    {{ checkedAllCities.length }}/{{ allocatedProArr.length }}
                  </el-col>
                </el-row>
                <el-form-item
                  label="区域"
                  class="row-padding-bottom"
                  style="margin-bottom: 18px"
                  v-if="isCzUser()"
                >
                  <el-cascader
                    ref="manageArea"
                    v-model="gridAreaId"
                    :append-to-body="false"
                    :options="areasOptions"
                    @change="getGridAreaId"
                    clearable
                    filterable
                    :props="{ checkStrictly: true }"
                    style="width: 70%"
                  ></el-cascader>
                </el-form-item>
                <el-form-item label="项目名称">
                  <el-select
                    v-model="formData.allocatedPro"
                    filterable
                    clearable
                    remote
                    reserve-keyword
                    placeholder="请输入"
                    :remote-method="remoteMethodAllocated"
                    @clear="clearOptionAllocated"
                    style="width: 70%"
                    @change="changeAllocated($event)"
                    value-key="id"
                  >
                    <el-option
                      v-for="item in options"
                      :key="item.id"
                      :label="item.projectName"
                      :value="item"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <ul class="selectDepart treeStyleList" id="choiceNameBox">
                  <el-checkbox-group
                    v-model="checkedAllCities"
                    @change="handleCheckedCitiesChangeAll"
                  >
                    <el-checkbox
                      v-for="item in allocatedProArr"
                      :label="item.id"
                      :key="item.id"
                      style="display: block"
                      >{{ item.projectName }}</el-checkbox
                    >
                  </el-checkbox-group>
                </ul>
                <div class="block">
                  <!-- <el-pagination layout="total,prev, pager, next" :total="total" :current-page.sync="pageNo" :page-size="pageSize" @size-change="handleSizeChange" @current-change="handleCurrentChange" :pager-count="4">
                                        </el-pagination> -->
                </div>
              </div>
            </el-col>
          </el-row>
        </el-form-item>
        <el-row
          style="
            text-align: center;
            margin-top: 45px;
            margin-top: 40px;
            margin-bottom: 24px;
          "
        >
          <el-col :span="20">
            <el-form-item>
              <el-button
                class="commonBut saveBtn disableSty"
                type="primary"
                :loading="isSubmit"
                v-sdc
                @click="sure"
                :disabled="allocatedProArr.length > 0 ? false : true"
                >确定</el-button
              >
              <el-button class="commonBut" @click="goBack">取消</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </div>
</template>
<script>
import { mapState, mapActions } from 'vuex'
export default {
  name: 'bnatchDistribution',
  components: {},
  data() {
    return {
      back: true,
      titleText: '分配项目',
      formData: {
        unallocatedPro: [],
        allocatedPro: [],
        gridMember: '',
        areaId: '',
        gridAreaId: '',
      },

      pageNo: 1,
      pageSize: 20,
      gridMemberArr: [], //网格员数组

      total: '',
      choiceArr: [],
      loading: false,
      newUnallocatedProArr: [],
      newUnallocatedProList: [],
      cancelArr: [],
      allUnallocatedProArr: [],
      choiceDisabled: true,
      cancelDisabled: true,
      options: [],
      isSubmit: false,
      allocatedMap: {},
      accumulationIds: [],
      areaId: '',
      gridAreaId: '',

      checked: false,
      isIndeterminate: false,
      unallocatedProArr: [], //未分配项目列表
      checkedCities: [], //选中的未分配的项目

      checkedAll: false,
      isIndeterminateAll: false,
      allocatedProArr: [], //
      checkedAllCities: [],

      filterLeftId: [],
      filterRightId: [],
      allocatedProArrSelected: [],
    }
  },
  computed: {
    ...mapState(['areasOptions']),
  },
  created() {
    this.getAreas({ areaId: this.$store.state.areaInfoArr.areaId })
    this.getUnallocatedPro(1, 20, '', '', '')
    this.getGridMemberList()
  },
  methods: {
    ...mapActions(['getAreas']),
    handleCheckChange(val) {
      this.checkedCities = []
      if (val) {
        this.unallocatedProArr.forEach((item) => {
          this.checkedCities.push(item.id)
        })
      }
      this.isIndeterminate = false
    },
    handleCheckedCitiesChange(value) {
      let checkedCount = value.length
      this.checked = checkedCount === this.unallocatedProArr.length
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.unallocatedProArr.length
    },
    handleCheckAllChange(val) {
      this.checkedAllCities = []
      if (val) {
        this.allocatedProArr.forEach((item) => {
          this.checkedAllCities.push(item.id)
        })
      }
      this.isIndeterminateAll = false
    },
    handleCheckedCitiesChangeAll(value) {
      let checkedCount = value.length
      this.checkedAll = checkedCount === this.allocatedProArr.length
      this.isIndeterminateAll =
        checkedCount > 0 && checkedCount < this.allocatedProArr.length
    },
    //向左移动
    cancel() {
      // if(this.allocatedProArrSelected.lenght > 0){
      //     this.allocatedProArr = this.allocatedProArrSelected.filter(item=>!this.checkedAllCities.includes(item.id))
      //     this.allocatedProArrSelected = []
      // }else{
      this.allocatedProArr = this.allocatedProArrSelected.filter(
        (item) => !this.checkedAllCities.includes(item.id)
      )
      this.allocatedProArrSelected = this.allocatedProArr
      // }

      this.filterLeftId = [
        ...new Set(this.filterLeftId.concat(this.checkedAllCities)),
      ]
      this.getUnallocatedPro(
        this.pageNo,
        this.pageSize,
        this.filterRightId.join(','),
        '',
        this.filterLeftId.join(',')
      )
      //    this.selectGrid()
      this.checkedAllCities = []
      this.checkedAll = false
      this.isIndeterminateAll = false
      this.formData.allocatedPro = []
      this.gridAreaId = ''
    },
    //向右移动
    confirm() {
      this.unallocatedProArr.forEach((item, index) => {
        if (this.checkedCities.includes(item.id)) {
          this.allocatedProArr.push(item)
        }
      })
      // this.allocatedProArrSelected = this.allocatedProArr
      this.filterRightId = [
        ...new Set(this.filterRightId.concat(this.checkedCities)),
      ]
      this.pageNo = 1
      this.getUnallocatedPro(
        this.pageNo,
        this.pageSize,
        this.filterRightId.join(','),
        '',
        this.filterLeftId.join(',')
      )
      this.checked = false
      this.checkedCities = []
      this.isIndeterminate = false
      this.formData.unallocatedPro = []
    },
    // 获取未分配项目列表
    getUnallocatedPro(pageNo, pageSize, projectIds, query, filterProjectIds) {
      var data = {
        pageNo: pageNo,
        pageSize: pageSize,
        projectIds: projectIds,
        projectName: query,
        filterProjectIds: filterProjectIds,
        areaId: this.formData.areaId,
      }
      this.axios({
        method: 'post',
        url: 'api-p/project/expand/findprolistbypage',
        data: data,
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              if (query) {
                this.newUnallocatedProList = response.data.result.results
                this.loading = true
                setTimeout(() => {
                  this.loading = false
                  this.newUnallocatedProArr = this.newUnallocatedProList.filter(
                    (item) => {
                      return (
                        item.projectName
                          .toLowerCase()
                          .indexOf(query.toLowerCase()) > -1
                      )
                    }
                  )
                }, 500)
                return
              } else {
                this.unallocatedProArr = response.data.result.results
                this.newUnallocatedProArr = []
              }

              var arr = response.data.result.results
              arr.forEach((item) => {
                var flag = false
                this.allUnallocatedProArr.forEach((item2) => {
                  if (item2.id == item.id) {
                    flag = true
                  }
                })
                if (!flag) {
                  this.allUnallocatedProArr.push(item)
                }
              })
              this.total = response.data.result.total

              this.checked = false
            }
          },
          (response) => {}
        )
        .catch((error) => {})
    },
    // 获取网格员
    getGridMemberList() {
      this.axios({
        method: 'post',
        url: 'api-p/grid/expand/findgridusers',
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              this.gridMemberArr = response.data.result
              if (!this.formData.gridMember || this.formData.gridMember == '') {
                this.formData.gridMember = this.gridMemberArr[0].userId
                this.selectGrid('init')
              }
            }
          },
          (response) => {}
        )
        .catch((error) => {})
    },
    // 切换网格员显示不同项目信息
    selectGrid(type) {
      if (
        (this.formData.gridMember != '' &&
          !(this.formData.gridMember in this.allocatedMap)) ||
        (this.formData.gridMember != '' && this.formData.gridAreaId != '')
      ) {
        this.axios({
          method: 'post',
          url: 'api-p/gridlink/expand/findbyuserid',
          data: {
            userId: this.formData.gridMember,
            areaId: this.formData.gridAreaId,
          },
        })
          .then(
            (response) => {
              if (!response.data.hasError) {
                // this.allocatedProArr = response.data.result;
                // if (!response.data.resul)
                this.allocatedMap[this.formData.gridMember] =
                  response.data.result
                this.allocatedProArr = response.data.result
                if (type) {
                  this.allocatedProArrSelected = this.allocatedProArr
                }
              }
            },
            (response) => {}
          )
          .catch((error) => {})
      } else {
        this.allocatedProArr = JSON.parse(
          JSON.stringify(this.allocatedMap[this.formData.gridMember])
        )
      }
    },
    handleCurrentChange(val) {
      this.getUnallocatedPro(
        val,
        this.pageSize,
        this.choiceArr.join(','),
        '',
        ''
      )
    },
    //保存
    sure() {
      this.isSubmit = true
      if (!this.formData.gridMember) {
        this.$message({
          message: '未选择分配网格管理员',
          type: 'warning',
        })
        this.isSubmit = false
        return
      }
      // if(this.allocatedProArr) {
      //     this.$message({
      //         message: "未选择分配项目",
      //         type: "warning"
      //     });
      //     return
      // }
      var ids = []
      for (var i = 0; i < this.allocatedProArr.length; i++) {
        ids.push(this.allocatedProArr[i].id)
      }
      this.axios({
        method: 'post',
        url: 'api-p/gridlink/expand/save',
        data: {
          userId: this.formData.gridMember,
          projectIds: ids.join(','),
        },
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              this.$message({
                message: '保存成功',
                type: 'success',
              })
              this.choiceArr = []
              this.$nextTick(function () {
                this.getUnallocatedPro(1, 20, '', '', '')
              })
            } else {
              this.$message({
                message: response.data.errorMsg,
                type: 'error',
              })
            }
            this.isSubmit = false
          },
          (response) => {}
        )
        .catch((error) => {
          this.isSubmit = false
        })
    },
    remoteMethod(query) {
      // this.getProList(query)
      this.getUnallocatedPro('1', '9999', this.choiceArr.join(','), query, '')
    },
    clearOption() {
      this.newUnallocatedProArr = []
      this.pageNo = 1
      this.getUnallocatedPro(
        this.pageNo,
        this.pageSize,
        this.choiceArr.join(','),
        '',
        ''
      )
    },
    changePro(ele) {
      this.unallocatedProArr = [ele]

      // this.checkedCities.push(ele.id)
      // this.options = []
      // this.confirm()
    },
    remoteMethodAllocated(query) {
      if (query !== '') {
        setTimeout(() => {
          this.options = this.allocatedMap[this.formData.gridMember].filter(
            (item) => {
              return (
                item.projectName.toLowerCase().indexOf(query.toLowerCase()) > -1
              )
            }
          )
        }, 200)
      } else {
        this.options = []
      }
    },
    clearOptionAllocated() {
      this.options = []
      // this.allocatedProArr = [];
      this.choiceArr.forEach((id) => {
        this.allUnallocatedProArr.forEach((item) => {
          if (item.id == id) {
            this.allocatedProArr.push(item)
            return
          }
        })
      })
      // this.allocatedProArrSelected = this.allocatedProArr
      this.selectGrid()
    },
    changeAllocated(ele) {
      // this.allocatedProArrSelected = this.allocatedProArr;
      this.allocatedProArr = [ele]
      // this.allocatedProArrSelected = [ele];
      this.checkedAllCities.push(ele.id)
      // this.options = []
      // this.cancel()
    },
    goBack() {
      this.$router.push('/home/networkGrid/networkGridTab')
      this.$store.commit('CHANGE_SLIDER_NAME', {
        oldUrl: '/home/networkGrid/networkGridTab',
        newUrl: this.$router.currentRoute.fullPath,
      })
    },
    //获取选中的区域最后一级id
    getAreaId() {
      var areaId = this.areaId[this.areaId.length - 1]
      this.formData.areaId = areaId
      this.getUnallocatedPro(1, 20, '', '', '')
    },
    getGridAreaId() {
      var areaId = this.gridAreaId[this.gridAreaId.length - 1]
      this.formData.gridAreaId = areaId
      this.selectGrid()
    },
  },
}
</script>

<style lang="less" scoped>
.mainCon {
  top: 209px;
  .formSty {
    margin-left: 9%;
  }
  /deep/ .el-form-department .el-form-item__content {
    margin-left: 0 !important;
    .treeStyle {
      width: 40%;
      .titleSty {
        background-color: #f5f7fa;
        text-align: left;
        margin-bottom: 12px;
        height: 60px;
        line-height: 60px;
        padding: 0 20px;
        .el-checkbox {
          margin-right: 10px;
        }
      }
      .treeStyleList {
        // border: 1px solid #eee;
        border-radius: 5px;
        padding: 20px;
        height: 370px;
        overflow-y: auto;
        margin-top: 12px;
      }
      .girdBox {
        border: 1px solid #eee;
        height: calc(100% - 0px);
        .selectAllSty {
          text-align: right;
        }
      }
      .choseTreeBut {
        display: block;
        margin: 0 auto;
        border: 0;
        font-size: 18px;
        background-color: #009588;
        border-color: #009588;
      }
      .choseTreeBut.is-disabled {
        opacity: 0.6;
      }
    }
  }
  .on {
    color: #009588;
  }
  .disableSty.is-disabled {
    color: #fff;
    background-color: #009588;
    border-color: #009588;
  }
}
.theme_default .on {
  color: #3189ea !important;
}
.theme_default .choseTreeBut {
  background-color: #3189ea !important;
  border-color: #3189ea !important;
}
.block {
  border-top: 1px solid #eee;
  height: 50px;
  padding: 10px 20px 6px;
}
.sums {
  text-align: right;
  color: #999;
}

// /deep/.el-checkbox__label {
// display: inline;
// }

// /deep/.el-checkbox, /deep/.el-checkbox__input {
// white-space: normal;
// }

// /deep/.el-checkbox__label {
//     white-space: normal;
//     word-break: break-all;
// }
</style>
